<?php


namespace app\index\controller;

use app\common\controller\IndexBase;
use app\common\model\Jdzcomment;
use app\common\model\Leader;
use app\common\model\Manager;
use app\common\model\Message;
use app\common\model\Score;
use app\common\model\Task;
use app\common\model\Work;

class Jdz extends IndexBase
{
    protected function _initialize()
    {

        parent::_initialize();
    }

    public function index()
    {
        $banner = model('Ads')->where('nid=3')->select();
        $this->assign('banner', $banner);
        return $this->fetch();
    }

    public function alljdz()
    {
        $work = new Work();
        $department = $work->get_department_list();
        $model = input('model', 0);
        $this->assign('model', $model);
        $this->assign('department', $department);
        return $this->fetch();
    }

    public function get_all_list()
    {
        input('title') ? $where['title'] = ['like', '%' . input('title') . '%'] : '';
        input('question_type') ? $where['question_classfyid'] = input('question_type') : '';
        input('depart_id') ? $where['departid'] = input('depart_id') : '';
//      input('status')?$where['status']=input('status'):$where['status']=['in',[4,10,12,13,14]];
        //input('status') ? $where['status'] = input('status') : '';
        input('page') ? $page = input('page') : 1;
        input('complete_type') ? $where['complete_type'] = input('complete_type') : '';
        if (input('complete_type') == 0) {
            $where['complete_type'] = ['in', '0,1,2,3'];
        }
        if (input('ismy')) {
            if (input('model') != 2) {
                $where['status'] = ['neq', ''];
                $where['user_id'] = session('user_info')['userid'];
            }
            if (input('model') == 2) {
                $task = new Task();
                $list = $task->where(['user_id' => session('user_info')['userid']])->column('jdz_id');
                $where['id'] = ['in', $list];
            }
        }
        $status = input('status');
        if($status =='100'){
           $where['status'] = ['in',[7,1,9,2,5,11,15,17,18]];
        }else{
            input('status') ? $where['status'] = input('status') : '';
        }
        $m = new \app\common\model\Jdz();
        $list = $m->where($where)->where($q)->order('add_time desc,status asc,appreciatenumber desc')->page($page, 5)->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function getlist()
    {
        if ($this->request->isAjax()) {
            $m = new \app\common\model\Jdz();
            return $m->getLists();
        }
    }

    public function myjdz()
    {
        $model = input('model', 1);
        $this->assign('model', $model);
        return $this->fetch();
    }

    public function detail()
    {
        $id = input('id');
        $rows = model('Jdz')->get($id);
        $my_department_id = $rows['propose_department_id'];
		//halt($rows);
        $leader = new Leader();
        $leader_info = $leader->where('department_id', '=', $rows['departid'])->find();
        $my_leader_info = $leader->where('department_id', '=', $my_department_id)->find();
        //是部门经理
        if (in_array(session('user_info')['userid'], json_decode($leader_info['leader_user_list'], true))) {
            $is_leader_user = 1;
        }
        //是我的部门经理
        if (in_array(session('user_info')['userid'], json_decode($my_leader_info['leader_user_list'], true))) {
            $is_my_leader_user = 1;
        }
        //是分管领导
        if (in_array(session('user_info')['userid'], json_decode($leader_info['class_user_list'], true))) {
            $is_class_user = 1;
        }
        //是我的分管领导
        if (in_array(session('user_info')['userid'], json_decode($my_leader_info['class_user_list'], true))) {
            $is_my_class_user = 1;
        }
        //是提议发布人
        if ($rows['user_id'] == session('user_info')['userid']) {
            $is_publish_user = 1;
        }
        //评估未完成，其他人
        /*
        if(in_array($rows['status'],[4,10,12,13,14])){
            $is_other_user =1;
        }
        */
        //是总经理
        $manager = new Manager();
        $managers = $manager->find(1);
        if (in_array(session('user_info')['userid'], json_decode($managers['list'], true))) {
            $is_manager = 1;
        }
        //是验收者
        /*
        $managers = $manager->find(2);

        if (in_array(session('user_info')['userid'], json_decode($managers['list'], true))) {
            $is_acceptor = 1;
        }
        */
        //是合作者
        if (in_array(session('user_info')['userid'], explode(',', $rows['partners_id']))) {
            $is_partner = 1;
        }
        //是指定人员
        if (in_array(session('user_info')['userid'], explode(',', $rows['complete_user_id']))) {
            $is_complete = 1;
        }
        //是否确认过
        $task = new Task();
        $t = $task->where(['user_id' => session('user_info')['userid'], 'jdz_id' => $rows['id']])->find();
        if ($t) {
            $is_sure = 1;
        }
        //任务被否定
        if ($task->where(['user_id' => session('user_info')['userid'], 'jdz_id' => $rows['id'], 'status' => 3])->find()) {
            $is_pass = 1;
        }
        //接任务的人并已经确认任务
        $task_user = $task->where(['jdz_id' => $rows['id'], 'status' => 1])->column('user_id');
        if (in_array(session('user_info')['userid'], $task_user)) {
            $is_task_user = 1;
        }
        if ($t['complete_content']) {
            $user_finish = 1;
        }
        //确认过任务
        if ($t['content'] && $task_user) {
            $is_sure_content = 1;
        }
        //已经接受任务
        if ($t['content']) {
            $has_sure = 1;
        }
        //是否评分
        $score = new Score();
        $s = $score->where(['user_id' => session('user_info')['userid'], 'jdz_id' => $rows['id']])->find();
        if ($s) {
            $is_score = 1;
        }
		//halt($my_leader_info);
        $next_status = $this->get_nextstatus($rows,
            json_decode($my_leader_info['leader_user_list'], true),
            json_decode($my_leader_info['class_user_list'], true),
            json_decode($leader_info['leader_user_list'], true),
            //json_decode($managers['list'], true),
            json_decode($leader_info['class_user_list'], true),
            json_decode($managers['list'], true)
        );
        //信息查看权限
        $this->assign('rows', $rows);
        $this->assign('next_status', $next_status);
        $this->assign('is_leader_user', $is_leader_user);
        $this->assign('is_class_user', $is_class_user);
        $this->assign('is_publish_user', $is_publish_user);
        $this->assign('is_manager', $is_manager);
        $this->assign('is_partner', $is_partner);
        $this->assign('is_complete', $is_complete);
        $this->assign('is_sure', $is_sure);
        $this->assign('is_pass', $is_pass);
        $this->assign('is_task_user', $is_task_user);
        $this->assign('user_finish', $user_finish);
        // $this->assign('is_acceptor', $is_acceptor);
        $this->assign('is_my_leader_user', $is_my_leader_user);
        $this->assign('is_my_class_user', $is_my_class_user);
        $this->assign('is_score', $is_score);
        $this->assign('has_sure', $has_sure);
        $this->assign('is_sure_content', $is_sure_content);
        return $this->fetch();
    }

    private function get_nextstatus($rows,
                                    $my_leader_list,
                                    $my_class_list,
                                    $leader_list,
                                    //$score_list,
                                    $class_list,
                                    $mamager)
    {
        $jdz_status = $rows['status'];
        if ($jdz_status == 15) {
            $str = '提议部门领导审核，审核人:';
            foreach ($my_leader_list as $v) {
                $str .= get_user_info($v)['name'];
            }
            return $str;
        }
        if ($jdz_status == 17) {
            $str = '提议部门分管领导审核，审核人：';
            foreach ($my_class_list as $v) {
                $str .= get_user_info($v)['name'];
            }
            return $str;
        }
        if ($jdz_status == 18) {
            $str = '提议部门分管领导评估，评估人：';
            foreach ($my_class_list as $v) {
                $str .= get_user_info($v)['name'];
            }
            return $str;
        }
        if (($jdz_status == 1) || ($jdz_status == 9)) {
            $str = '问题部门领导审核，审核人：';
            foreach ($leader_list as $v) {
                $str .= get_user_info($v)['name'];
            }
            return $str;
        }

        if (($jdz_status == 2) || ($jdz_status == 11)) {
            $str = '问题部门分管领导评估，评估人：';
            foreach ($class_list as $v) {
                $str .= get_user_info($v)['name'];
            }
            return $str;
        }
        if ($jdz_status == 5) {
            $str = '问题部门分管领导采纳，采纳人：';
            foreach ($class_list as $v) {
                $str .= get_user_info($v)['name'];
            }
            return $str;
        }
        if ($jdz_status == 7) {
            $str = '待总经理审核。审核人：';
            foreach ($mamager as $v) {
                $str .= get_user_info($v)['name'];
            }
            return $str;
        }
        if (($jdz_status == 4) || ($jdz_status == 12)) {

            $task = new Task();
            $task_list = $task->where(['jdz_id' => $rows['id'], 'status' => ['neq', 0]])->select()->toArray();
            if (!$task_list) {
                return '待员工接任务';
            }

            foreach ($task_list as $v) {
                if (($v['content'] == null) || ($v['content'] == '')) {
                    $accept .= get_user_info($v['user_id'])['name'];
                } else {
                    if (($v['complete_content'] == null) || ($v['complete_content'] == '')) {
                        $complete .= get_user_info($v['user_id'])['name'];
                    }
                }
            }
            if ($accept) {
                $str = '待' . $accept . '接受任务';
            }
            if ($complete) {
                $str .= '待' . $complete . '完成任务';
            }
            return $str;
        }
        if ($jdz_status == 19) {
            $str = '待提议人确认任务完成，确认人：' . $rows['user_name'];
            return $str;
        }
        if ($jdz_status == 13) {
            $str = '待评分人进行评分，评分人：';
            foreach ($leader_list as $v) {
                $k[] = $v;
            }
            foreach ($class_list as $v) {
                $k[] = $v;
            }
            //$k = array_unique($k);
            foreach ($k as $v) {
                $str .= get_user_info($v)['name'];
            }
            return $str;
        }
        //结束
        if ($jdz_status == 14) {
            return 1;
        }
        //关闭
        return 2;

    }

    public function publish_jdz()
    {
        if ($this->request->isAjax()) {
            $data = input();
            $data['add_time'] = date('Y-m-d H:i:s');
            //$data['status'] = 1;
            $data['status'] = 15;
            $data['user_id'] = session('user_info')['userid'];
            $data['user_head'] = session('user_info')['avatar'];
            $data['user_name'] = session('user_info')['name'];
			if(session('user_info')['main_department']){
				$data['propose_department_id'] = session('user_info')['main_department'];
			}else{
				$data['propose_department_id'] = session('user_info')['department'][0];
			}
            if($data['is_right'] == 1){
                if(!$data['right_type']){
                    return ajax_return(2,'请选择知识产权类型');
                }
            }
            //halt($data);
            $data['log'] = json_encode([[
                'times' => time(),
                'user' => session('user_info')['userid'],
                'user_name' => session('user_info')['name'],
                'user_head' => session('user_info')['avatar'],
                'type' => 1,
                'message' => '发布提议',
                'content' => '']]);
            $m = new \app\common\model\Jdz();
            return $m->_save($data);
        }
        return $this->fetch();
    }

    public function revive()
    {
        $id = input('id');
        $jdz = new \app\common\model\Jdz();
        $rows = $jdz->find($id);
        if ((!in_array($rows['status'], [3, 6, 16])) || ($rows['user_id'] != session('user_info')['userid'])) {
            $this->error('此提议无法复活，或者复活权限不足');
        }
        if ($this->request->isAjax()) {
            $data = input();
            switch ($rows['status']) {
                case 3:
                    $data['status'] = 5;
                    break;
                case 6:
                    $data['status'] = 7;
                    break;
                case 16:
                    $data['status'] = 17;
                    break;
                default:
                    $data['status'] = 5;
            }
            $log = json_decode($rows['log'], true);
            $log[] = [
                'times' => time(),
                'user' => session('user_info')['userid'],
                'user_name' => session('user_info')['name'],
                'user_head' => session('user_info')['avatar'],
                'type' => $data['status'],
                'message' => '复活提议',
                'content' => ''];
            $data['log'] = json_encode($log);
            $data = array_merge($rows->toArray(), $data);
            return $jdz->_save($data);

        }
        $this->assign('rows', $rows);
        return $this->fetch();
    }

    /**部门经理提议评估
     *
     */
    public function adopt()
    {
        $id = input('id');
        $jdz = new \app\common\model\Jdz();
        $info = $jdz->find($id);
        $leader = new Leader();
        $leader_info = $leader->where('department_id', '=', $info['departid'])->find();
        $my_department_id = $info['propose_department_id'];
        $my_leader_info = $leader->where('department_id', '=', $my_department_id)->find();
        /*
        //是我的部门经理
        if (in_array(session('user_info')['userid'], json_decode($my_leader_info['leader_user_list'], true))) {
            $is_leader_user = 1;
        }
        //是部门经理
        if (in_array(session('user_info')['userid'], json_decode($leader_info['leader_user_list'], true))) {
            $is_leader_user = 1;
        }
        if (!$is_leader_user) {
            $this->error('采纳权限不足');
        }
        */
        if ($this->request->isAjax()) {
            $data = input();
            if (input('adopt') == 1) {
                switch ($info['status']) {
                    //部门经采纳
                    case 1:
                        $data['status'] = 4;
                        break;
                    //分管领导采纳
                    case 5:
                        $data['status'] = 4;
                        break;
                    //总经理采纳
                    case 7:
                        $data['status'] = 4;
                        break;
                    case 9:
                        $data['status'] = 11;
                        break;
                    //提议部门领导采纳
                    case 15:
                        $data['status'] = 18;
                        break;
                    case 17:
                        $data['status'] = 1;
                        break;
                    default:
                        $data['status'] = 4;
                }
                $message = '采纳提议';
            } else {
                switch ($info['status']) {
                    //部门经理不采纳
                    case 1:
                        $data['status'] = 3;
                        break;
                    //分管领导不采纳
                    case 5:
                        $data['status'] = 6;
                        break;
                    //总经理不采纳
                    case 7:
                        $data['status'] = 8;
                        break;
                    case 9:
                        $data['status'] = 10;
                        break;
                    //提议部门领导不采纳
                    case 15:
                        $data['status'] = 16;
                        break;
                    case 17;
                        $data['status'] = 6;
                        break;
                    default:
                        $data['status'] = 3;
                }
                $message = '不采纳提议';
            }
            $log = json_decode($info['log'], true);
            $log[] = [
                'times' => time(),
                'user' => session('user_info')['userid'],
                'user_name' => session('user_info')['name'],
                'user_head' => session('user_info')['avatar'],
                'type' => $data['status'],
                'message' => $message,
                'content' => $data['adopt_reason'],
                //'department'=>$data['department']
                ];
            $data['log'] = json_encode($log);
            //第一次复活后，分管领导审核信息
            if ($info['status'] == 5) {
                $data['class_reason'] = $data['adopt_reason'];
                $data['adopt_reason'] = $info['adopt_reason'];
            }
            if ($info['status'] == 7) {
                $data['manager_reason'] = $data['adopt_reason'];
                $data['adopt_reason'] = $info['adopt_reason'];
            }
            $data['adopt_time'] = date('Y-m-d H:i:s');
            $data = array_merge($info->toArray(), $data);
            return $jdz->_save($data);
        }
        $this->assign('rows', $info);
        return $this->fetch();
    }

    /**分管领导提议评估
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function class_adopt()
    {
        $id = input('id');
        $jdz = new \app\common\model\Jdz();
        $info = $jdz->find($id);
        $leader = new Leader();
        $leader_info = $leader->where('department_id', '=', $info['departid'])->find();
        if (in_array(session('user_info')['userid'], json_decode($leader_info['class_user_list'], true))) {
            $is_class_user = 1;
        }
        $my_department_id = $info['propose_department_id'];
        $my_leader_info = $leader->where('department_id', '=', $my_department_id)->find();
        //是我的部门经理
        if (in_array(session('user_info')['userid'], json_decode($my_leader_info['leader_user_list'], true))) {
            $is_class_user = 1;
        }
//        if (!$is_class_user) {
//            $this->error('评估权限不足');
//        }
        if ($this->request->isAjax()) {
            $data = input();
            if($data['do']==1) {
                if ($info['status'] == 11) {
                    $data['status'] = 12;
                } elseif ($info['status'] == 18) {
                    $data['status'] = 1;
                }
                $message = '已评估';
            }else{
                $data['status'] =6;
                $message = '不采纳';
            }
            $log = json_decode($info['log'], true);
            $log[] = [
                'times' => time(),
                'user' => session('user_info')['userid'],
                'user_name' => session('user_info')['name'],
                'user_head' => session('user_info')['avatar'],
                'type' => $data['status'],
                'message' => $message,
                'content' => $data['class_reason'],
                'department'=>$data['department']
            ];
            $data['log'] = json_encode($log);
            $data = array_merge($info->toArray(), $data);
            return $jdz->_save($data);
        }
        $this->assign('rows', $info);
        return $this->fetch();
    }

    public function adoptjdz()
    {
        $leader = new Leader();
        $department = $leader->where(['leader_user_list' => ['like', '%"' . session('user_info')['userid'] . '"%']])->whereOr(['class_user_list' => ['like', '%"' . session('user_info')['userid'] . '"%']])->column('department_id');
        $leader_department = $leader->where(['leader_user_list' => ['like', '%"' . session('user_info')['userid'] . '"%']])->column('department_id');
        $class_department = $leader->where(['class_user_list' => ['like', '%"' . session('user_info')['userid'] . '"%']])->column('department_id');
        //如果是总经理
        $manager = new Manager();
        $managers = $manager->find(1);
        $manage = json_decode($managers['list'], true);
        if (in_array(session('user_info')['userid'], $manage)) {
            $q[] = "(`status`=7)";
        }
        if ($leader_department) {
            $q[] = "( `status` in (1,9) AND `departid` IN (" . implode(',', $leader_department) . "))";
        }
        if ($class_department) {
            $q[] = "( `status` IN (2,5,11) AND `departid` IN (" . implode(',', $class_department) . "))";
        }
        $my_id = session('user_info')['userid'];
        $my_leader_info = $leader->where(['leader_user_list' => ['like', '%' . $my_id . '%']])->column('department_id');
        $my_class_info = $leader->where(['class_user_list' => ['like', '%' . $my_id . '%']])->column('department_id');
        if ($my_leader_info) {
            $q[] = "( `status` IN (15) AND `propose_department_id` IN (" . implode(',', $my_leader_info) . "))";
        }
        if ($my_class_info) {
            $q[] = "( `status` IN (17,18) AND `propose_department_id` IN (" . implode(',', $my_leader_info) . "))";
        }
        $q = implode(' OR ', $q);
        if(!$q){
            $this->error('权限不足');
        }
        $query = "SELECT * FROM `hs_jdz` WHERE ( 1 AND (" . $q . "))";
        $jdz = new \app\common\model\Jdz();
        $list = $jdz->query($query);
        $this->assign('list', $list);
        return $this->fetch();
    }

    public function joinjdz()
    {
        $work = new Work();
        $department = $work->get_department_list();
        $model = input('model', 4);
        $this->assign('model', $model);
        $this->assign('department', $department);
        return $this->fetch();
    }

    public function get_join_list()
    {
        input('title') ? $where['title'] = ['like', '%' . input('title') . '%'] : '';
        input('question_type') ? $where['question_classfyid'] = input('question_type') : '';
        input('page') ? $page = input('page') : 1;
        //input('complete_type')?$where['complete_type']=input('complete_type'):'';// 1我提你改2自提自改3寻求合作4等待评估5复活提议
        //等待评估的问题
        $jdz = new \app\common\model\Jdz();
        $leader = new Leader();
        $department = $leader->where(['leader_user_list' => ['like', '%"' . session('user_info')['userid'] . '"%']])->whereOr(['class_user_list' => ['like', '%"' . session('user_info')['userid'] . '"%']])->column('department_id');

        //等待评估的提议
        if (input('complete_type') == 4) {
            $where['status'] = ['in', [1, 2]];
            $where['departid'] = ['in', $department];
        }
        //等待复活的提议
        if (input('complete_type') == 5) {
            $where['status'] = ['in', [5, 7]];
            $where['departid'] = ['in', $department];
        }
        if (input('depart_id')) {
            if (in_array(input('depart_id'), $department)) {
                $where['departid'] = input('depart_id');
            }
        }
        //待完成的提议
        if (in_array(input('complete_type'), [1, 2, 3])) {
            $where['status'] = ['in', [4, 10, 12]];
            $where['complete_type'] = input('complete_type');
        }
        $list = $jdz->where($where)->page($page, 5)->select();
        $this->assign('list', $list);
        return $this->fetch('get_all_list');
    }

//    确认金点子
    public function confirm_jdz()
    {
        $id = input('jdz_id');
        $conform_content = input('confirm_content');
        $jdz = new \app\common\model\Jdz();
        $rows = $jdz->find($id);
        $log = json_decode($rows['log'], true);
        $task = new Task();
        /*
        $is_sure = $task->where(['jdz_id' => $id, 'user_id' => session('user_info')['userid'], 'status' => ['neq', 3]])->find();
        if ($is_sure) {
            return ajax_return(0, '您已经确认可该提议，无需再次确认！');
        }
        */
        /*
        $count = $task->field('count(id) as count')->where(['jdz_id' => $id])->find();
        if ($count['count'] > 3) {
            return ajax_return(0, '参与人数已经达到三人，无法再次参与');
        }
        */
        $data['jdz_id'] = $id;
        $data['user_id'] = session('user_info')['userid'];
        $data['content'] = $conform_content;
        $data['add_time'] = date('Y-m-d H:i:s');
        $data['status'] = 0;
        $complete_user_id = explode(',', $rows['complete_user_id']);
        $partners = explode(',', $rows['partners_id']);
        if (in_array(session('user_info')['userid'], $complete_user_id) || in_array(session('user_info')['userid'], $partners)) {
            $data['status'] = 1;
        }
        $has_l = $task->where(['jdz_id' => $id, 'user_id' => session('user_info')['userid']])->find();
        if (!$has_l) {
            $res = $task->insertGetId($data);
        } else {
            $task->save($data, ['id' => $has_l['id']]);
            $res = $has_l['id'];
        }
        if ($data['status'] == 0) {
            $msg = '接受任务，等待审核';
        } else {
            $msg = '接受任务';
        }
        if ($res) {
            $log[] = [
                'times' => strtotime($data['add_time']),
                'user' => session('user_info')['userid'],
                'user_name' => session('user_info')['name'],
                'user_head' => session('user_info')['avatar'],
                'type' => 15,
                'message' => $msg,
                'content' => $conform_content
            ];
            //提醒问题部门领导确认任务
            if ($data['status'] == 0) {
                $leader = new Leader();
                $leader_info = $leader->where(['department_id' => $rows['departid']])->find();
                $leader_user_list = json_decode($leader_info['leader_user_list']);
                $message = new Message();
                $work = new Work();
                foreach ($leader_user_list as $v) {
                    $message->send_message($v, '有人接取了任务，请前往确认是否有能力完成', '3', url('jdz/confirm_task', ['id' => $res]));
                }
                $work->send_templete_message($leader_user_list, '任务确认通知', '有人接取了任务，请前往确认是否有能力完成', site_url . '/index/jdz/confirm_task?id='.$res);
            }
            $info['log'] = json_encode($log);
            $info['id'] = $id;
            $jdz->save($info, $id);
        }
        return ajax_return(1, '确认成功');
    }

    public function comment()
    {
        $id = input('id');
        $jdz = new \app\common\model\Jdz();
        $score = new Score();
        $is_score = $score->where(['user_id' => session('user_info')['userid'], 'jdz_id' => $id])->find();
        $has_score = $score->where(['jdz_id' => $id])->select()->toArray();
        $acc_count = 0;
        $acc_score = 0;
        $user_count = 0;
        $user_score = 0;
        foreach ($has_score as $k => $v) {
            if ($v['user_type'] == 1) {
                $acc_count++;
                $acc_score = $acc_score + $v['score'];
            } else {
                $user_count++;
                $user_score = $user_score + $v['score'];
            }

        }
        //是验收者
        $manager = new Manager();
        $managers = $manager->find(2);
        if (in_array(session('user_info')['userid'], json_decode($managers['list'], true))) {
            $is_acceptor = 1;
        }
        $final_score = round(($acc_score / $acc_count), 2);
        $this->assign('final_score', $final_score);
        $rows = $jdz->get($id);
        $this->assign('is_score', $is_score);
        $this->assign('is_acceptor', $is_acceptor);
        $this->assign('rows', $rows);
        return $this->fetch();
    }

    public function publish_comment()
    {
        if ($this->request->isAjax()) {
            $comment = new Jdzcomment();
            $data['user_id'] = session('user_info')['user_id'];
            $data['user_head'] = session('user_info')['avatar'];
            $data['user_name'] = session('user_info')['name'];
            $data['content'] = input('comment');
            $data['add_time'] = date('Y-m-d H:i:s');
            $data['jdz_id'] = input('id');
            $res = $comment->save($data);
            model('jdz')->where(['id' => input('id')])->setInc('commentnumber');
            if ($res !== false) {
                $user = new \app\common\model\User();
                $roule = model('System')->getValue('roule_config');
                $user->put_exp(2, $roule['jdz_comment_exp'], $data['jdz_id']);
                $user->put_integral(2,$roule['jdz_comment_integral'],$data['jdz_id']);
                return ajax_return(1, '评论成功');
            }
            return ajax_return(0, '评论失败');
        }
    }

    public function get_comment_list()
    {
        $jdz_id = input('jdz_id');
        //$topic_info = model('Topic')->find($topic_id);
        //$this->assign('topic_info',$topic_info);
        $page = input('page') ? input('page') : 1;
        $comment = new Jdzcomment();
        $list = $comment->where(['jdz_id' => $jdz_id, 'status' => 1])->order('add_time desc')->page($page, 10)->select();
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**完成金点子
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function finish_jdz()
    {
        if ($this->request->isAjax()) {
            $id = input('jdz_id');
            $conform_content = input('finish_content');
            $file_url1 = input('file_url1');
            $file_url2 = input('file_url2');
            $file_url3 = input('file_url3');
            $data['jdz_id'] = $id;
            $data['complete_time'] = date('Y-m-d H:i:');
            $data['complete_content'] = $conform_content;
            $data['file_url'] = $file_url;
            $data['status'] = 2;
            $task = new Task();
            $t = $task->where(['user_id' => session('user_info')['userid'], 'status' => ['in', '1,2'], 'jdz_id' => $id])->find();
            if (!$t) {
                return ajax_return(0, '您未接此提议的任务，无法进行完成操作');
            }
            $data['id'] = $t['id'];
            $task->save($data, $t['id']);
            $jdz = new \app\common\model\Jdz();
            $info = $jdz->find($id);
            $log = json_decode($info['log'], true);
            $log[] = [
                'times' => time(),
                'user' => session('user_info')['userid'],
                'user_name' => session('user_info')['name'],
                'user_head' => session('user_info')['avatar'],
                'type' => 16,
                'message' => '完成任务',
                'content' => $conform_content,
                'file_url' => json_encode([$file_url1,$file_url2,$file_url3],JSON_UNESCAPED_UNICODE)
            ];
            $j['log'] = json_encode($log);
            //是否全部完成
            $finish_status = $jdz->get_finish_status($id);

            if ($finish_status) {
                $j['status'] = 19;
                $j['finish_time'] = date('Y-m-d H:i:s');
            }
            $j = array_merge($info->toArray(), $j);
            return $jdz->_save($j);
        }
        return $this->fetch();
    }

    /**获取列表
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function acceptor_jdz()
    {

//        $manager = new Manager();
//        $acc = $manager->find(2);
//        $managers = json_decode($acc['list'], true);
////        if (!in_array(session('user_info')['userid'], $managers)) {
////            $this->error('权限不足');
////        }
///
        $leader = new Leader();
        $depatid = $leader
            //->fetchSql(true)
            ->where(['class_user_list'=>['like','%'.session('user_info')['userid'].'%']])
            ->whereOr(['leader_user_list'=>['like','%'.session('user_info')['userid'].'%']])
            ->column('department_id');
        $title = input('title');
        if ($title) {
            $where['title'] = ['like', '%' . $title . '%'];
        }
        $where['departid'] = ['in',$depatid];
        $score = new Score();
        $has_score = $score->where(['user_id' => session('user_info')['userid']])->column('jdz_id');
        if (input('model') == 2) {
            $where['id'] = ['in', $has_score];
        } else {
            $where['id'] = ['not in', $has_score];
        }
        $where['status'] = ['in', [13, 14]];
        $jdz = new \app\common\model\Jdz();
        $list = $jdz->where($where)->select();
        $this->assign('model', input('model', 1));
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**提议完成评分
     * @return array|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function acceptor()
    {
        $id = input('id');
        $this->assign('id', $id);
        $score = new Score();
        $info = $score->where(['user_id' => session('user_info')['userid'], 'jdz_id' => $id])->find();
        if ($info) {
            $this->error('您已经评分了');
        }

        if ($this->request->isAjax()) {
            $rows = model('jdz')->find(input('id'));
            $leader = new Leader();
            $leader_info = $leader->where('department_id', '=', $rows['departid'])->find();
            $leader_user = json_decode($leader_info['leader_user_list'],true);
            $class_user = json_decode($leader_info['class_user_list'],true);
            if((!in_array(session('user_info')['userid'],$leader_user))&&(!in_array(session('user_info')['userid'],$class_user))){
                return ajax_return(0,'评分权限不足');
            }
            $score1 = input('score1');
            $score2 = input('score2');
            $score3 = input('score3');
            $score4 = input('score4');
            $score5 = input('score5');
            $score6 = input('score6');
            $data['jdz_id'] = input('id');
            $data['score'] = ($score1 * 0.15) + ($score2 * 0.15) + ($score3 * 0.15) + ($score4 * 0.15) + ($score5 * 0.25) + ($score6 * 0.15);
            $data['user_id'] = session('user_info')['userid'];
            $data['add_time'] = date('Y-m-d H:i:s');
            //部门领导评分
            if(in_array(session('user_info')['userid'],$leader_user)){
                $data['user_type'] = 1;
            }
//            分管领导评分
            if(in_array(session('user_info')['userid'],$class_user)){
                $data['user_type'] = 2;
            }
            $jdz = new \app\common\model\Jdz();
            $jdz_info = $jdz->find($data['jdz_id']);
            $log = json_decode($jdz_info['log'], true);
            $log[] = [
                'times' => time(),
                'user' => session('user_info')['userid'],
                'user_name' => session('user_info')['name'],
                'user_head' => session('user_info')['avatar'],
                'type' => 17,
                'message' => '评分',
                'content' => $data['score'] . '分'
            ];
            //halt($log);
            $log = json_encode($log);
            if ($score->save($data) !== false) {
                //部门领导和分管领导都评分完毕后，修改提议状态为已完成
                $do_leader = $score->where(['jdz_id'=>$data['jdz_id'],'user_type'=>1])->find();
                $do_class = $score->where(['jdz_id'=>$data['jdz_id'],'user_type'=>2])->find();
                $acc['log'] = $log;
                if ($do_leader&&$do_class) {
                    $acc['status'] = 14;
                }
                $acc = array_merge($jdz_info->toArray(), $acc);
                $jdz->_save($acc);
                return ajax_return(1, '评分成功', url('jdz/detail', ['id' => $data['id']]));
            }
            return ajax_return(0, '评分失败');
        }
        return $this->fetch();
    }

    /** 排行榜
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function rank()
    {
//        $data = model('user')->select();
//        foreach ($data as $v){
//            $user_info = get_user_info($v['user_id']);
//            $save_data['avatar'] =$user_info['avatar'];
//            $save_data['name'] =$user_info['name'];
//            model('user')->isUpdate(true)->save($save_data,['user_id'=>$v['user_id']]);
//        }
//        die;

        $type = input('type', 1);//1个人2部门3月度五佳4年度五佳5奖金榜
        $model = input('model', 1);//1提议数量2接棒次数3实施次数4累计得分
        $jdz = new \app\common\model\Jdz();
        $task = new Task();
        $user = new \app\common\model\User();
        if ($type == 1) {
            //提议榜
            if ($model == 1) {
                $jdz_list = $jdz->field('count(id) as count,user_id')->group('user_id')->select()->toArray();
                $sort = array_column($jdz_list, 'count');
                array_multisort($sort, SORT_DESC, $jdz_list);
                $this->assign('list', $jdz_list);
            }
            //揭榜
            if ($model == 2) {
                $task_list = $task->field('count(id) as count,user_id')->group('user_id')->select()->toArray();
                $sort = array_column($task_list, 'count');
                array_multisort($sort, SORT_DESC, $task_list);
                $this->assign('list', $task_list);
            }
            //实施
            if ($model == 3) {
                $task_list = $task->field('count(id) as count,user_id')->where(['complete_content' => ['neq', '']])->group('user_id')->select()->toArray();
                $sort = array_column($task_list, 'count');
                array_multisort($sort, SORT_DESC, $task_list);
                $this->assign('list', $task_list);
            }
            //得分
            if ($model == 4) {
                $user_list = $user->field('user_id,integral')->order('integral desc')->select()->toArray();
                $this->assign('list', $user_list);
            }
        }
        if ($type == 2) {
            if ($model == 1) {
                $jdz_list = $jdz->field('departid,department,count(id) as count')->group('departid')->select()->toArray();
                $sort = array_column($jdz_list, 'count');
                array_multisort($sort, SORT_DESC, $jdz_list);
                $this->assign('list', $jdz_list);
            }
            $work = new Work();
            if ($model == 2) {
                $deparmentlist = $work->get_department_list();
                foreach ($deparmentlist['department'] as $k => $v) {
                    $user_list[$k] = get_userlist_bydepartmentid($v['id'], 0);
                    foreach ($user_list[$k]['userlist'] as $u_v) {
                        $user_lists[$v['id']][] = $u_v['userid'];
                    }
                    $task_list[$v['id']] = $task->field('count(id) as count')->where(['user_id' => ['in', $user_lists[$v['id']]]])->find()->toArray();
                    $task_list[$v['id']]['name'] = $v['name'];
                }
                $this->assign('list', $task_list);
            }
            if ($model == 3) {
                $deparmentlist = $work->get_department_list();
                foreach ($deparmentlist['department'] as $k => $v) {
                    $user_list[$k] = get_userlist_bydepartmentid($v['id'], 0);
                    foreach ($user_list[$k]['userlist'] as $u_v) {
                        $user_lists[$v['id']][] = $u_v['userid'];
                    }
                    $task_list[$v['id']] = $task->field('count(id) as count')->where(['user_id' => ['in', $user_lists[$v['id']]], 'complete_content' => ['neq', '']])->find()->toArray();
                    $task_list[$v['id']]['name'] = $v['name'];
                }
                $this->assign('list', $task_list);
            }
            if ($model == 4) {
                $deparmentlist = $work->get_department_list();
                foreach ($deparmentlist['department'] as $k => $v) {
                    $user_list[$k] = get_userlist_bydepartmentid($v['id'], 0);
                    foreach ($user_list[$k]['userlist'] as $u_v) {
                        $user_lists[$v['id']][] = $u_v['userid'];
                    }
                    $list[$v['id']] = $user->field('sum(integral) as sum ')->where(['user_id' => ['in', $user_lists[$v['id']]]])->find()->toArray();
                    $list[$v['id']]['name'] = $v['name'];
                }
                $this->assign('list', $list);
            }
        }
        if ($type == 3) {
            $date = date("Y-m", strtotime('-1 month'));
            $begintime = $date . '-1 00:00:00';
            $endtime = date('Y-m-d', strtotime("$begintime +1 month -1 day")) . ' 23:59:59';
            $sql = "'$begintime' < `add_time` AND `add_time`< '$endtime' AND `status`=14";
            $jdz = new \app\common\model\Jdz();
            $list = $jdz->where($sql)->select();
            $score = new Score();
            foreach ($list as $k => $v) {
                $jdz_list[$k]['id'] = $v['id'];
                $score_1[$k] = $score->field('count(id) as count,sum(score) as sum')->where(['jdz_id' => $v['id']])->find()->toArray();
                $jdz_list[$k]['score'] =$score_1[$k]['sum'] / $score_1[$k]['count'] ;
                $jdz_list[$k]['title'] = $v['title'];
                $jdz_list[$k]['user_head'] = $v['user_head'];
                $jdz_list[$k]['user_name'] = $v['user_name'];
            }
            $sort = array_column($jdz_list, 'score');
            array_multisort($sort, SORT_DESC, $jdz_list);
            $this->assign('list', $jdz_list);
        }
        if ($type == 4) {
            $date = date("Y");
            $begintime = $date . '-1-1 00:00:00';
            $endtime = $date . '-12-31 23:59:59';
            $sql = "'$begintime' < `add_time` AND `add_time`< '$endtime' AND `status`=14";
            $jdz = new \app\common\model\Jdz();
            $list = $jdz->where($sql)->select();
            $score = new Score();
            foreach ($list as $k => $v) {
                $jdz_list[$k]['id'] = $v['id'];
                $score_1[$k] = $score->field('count(id) as count,sum(score) as sum')->where(['jdz_id' => $v['id']])->find()->toArray();
                $jdz_list[$k]['score'] = $score_1[$k]['sum'] / $score_1[$k]['count'];
                $jdz_list[$k]['title'] = $v['title'];
                $jdz_list[$k]['user_head'] = $v['user_head'];
                $jdz_list[$k]['user_name'] = $v['user_name'];
            }
            $sort = array_column($jdz_list, 'score');
            array_multisort($sort, SORT_DESC, $jdz_list);
            $this->assign('list', $jdz_list);
        }
        if ($type == 5) {
            $list = $user->order('amount desc')->select();
            $this->assign('list', $list);
        }
        $this->assign('type', $type);
        $this->assign('model', $model);
        return $this->fetch();
    }

    public function supp_jdz()
    {
        $id = input('id');
        $rows = model('jdz')->find($id);
        if (!in_array($rows['status'], [4, 10, 12])) {
            $this->error('提议处于不可补充状态，请确认');
        }
        if ($this->request->isAjax()) {
            $data = input();
            // $data['status'] = 9;
            $data['supp_user'] = session('user_info')['userid'];
            $data['supp_username'] = session('user_info')['name'];
            $log = json_decode($rows['log'], true);
            //halt($data);
            $log[] = [
                'times' => time(),
                'user' => session('user_info')['userid'],
                'user_name' => session('user_info')['name'],
                'user_head' => session('user_info')['avatar'],
                'type' => 1,
                'message' => '补充提议',
                'content' => $data['supp']];
            $rows = $rows->toArray();
            $data['departid'] = $rows['departid'];
            $data['propose_department_id'] = $rows['propose_department_id'];
            $data['id'] = $rows['id'];
            $data['log'] = json_encode($log);
            //$data = array_merge($rows, $data);
            return model('jdz')->_save($data);
        }
        $this->assign('rows', $rows);
        return $this->fetch();
    }

    public function confirm_task()
    {
        $id = input('id');
        $task = new Task();
        $task_info = $task->find($id)->toArray();
        $this->assign('task_info', $task_info);
        $jdz = new \app\common\model\Jdz();
        $jdz_info = $jdz->find($task_info['jdz_id']);
        $leader = new Leader();
        $leader_info = $leader->where(['department_id' => $jdz_info['departid']])->find();
        $leader_user_list = json_decode($leader_info['leader_user_list'], true);
        if (!in_array(session('user_info')['userid'], $leader_user_list)) {
            return $this->error('没有确认权限');
        }
        if ($task_info['status'] > 0) {
            return $this->error('任务已经确认完成，无需再次确认');
        }
        $this->assign('jdz_info', $jdz_info);
        if ($this->request->isAjax()) {
            $data['id'] = input('id');
            $data['status'] = input('status');
            if (($task->save($data, ['id' => $data['id']])) !== false) {
                $message = new Message();
                $work = new Work();
                if ($data['status'] == 1) {
                    $message->send_message($task_info['user_id'], '您的任务已经审批通过，请前往确认', '3', url('jdz/detail', ['id' => $task_info['jdz_id']]));
                    $work->send_templete_message([$task_info['user_id']], '任务审批通知', '您的任务已经审批通过，请前往确认', site_url .'/index/jdz/detail?id='.$task_info['jdz_id']);
                    $msg = '接受任务，已审核通过';
                } else {
                    $message->send_message($task_info['user_id'], '您的任务已经审批未通过，请前往确认', '3', url('jdz/detail', ['id' => $task_info['jdz_id']]));
                    $work->send_templete_message([$task_info['user_id']], '任务审批通知', '您的任务已经审批未通过，请前往确认', site_url .'/index/jdz/detail?id='.$task_info['jdz_id']);
                    $msg = '接受任务，审核未通过';
                }
                $log = json_decode($jdz_info['log'], true);
                foreach ($log as $k => $v) {
                    $save_log[$k] = $v;
                    if (($v['times'] == strtotime($task_info['add_time'])) && ($v['user'] == $task_info['user_id'])) {
                        $save_log[$k]['message'] = $msg;
                    }
                }
                model('jdz')->isUpdate(true)->save(['id' => $jdz_info['id'], 'log' => json_encode($save_log)]);
                return ['code' => 1, 'msg' => '操作完成'];
            }
        }
        return $this->fetch();
    }

    public function task_list()
    {
        $id = input('id');
        $task = new Task();
        $list = $task->where('jdz_id', '=', $id)->select();
        $this->assign('list', $list);
        $jdz = new \app\common\model\Jdz();
        $jdz_info = $jdz->where(['id' => $task[0]['jdz_id']])->find();
        $leader = new Leader();
        $leader_info = $leader->where('department_id', '=', $jdz_info['departid'])->find();
        //是部门经理
        if (in_array(session('user_info')['userid'], json_decode($leader_info['leader_user_list'], true))) {
            $is_leader_user = 1;
        }
        if (session('user_info')['userid'] == $jdz_info['user_id']) {
            $is_publish = 1;
        }
        $this->assign('is_leader_user', $is_leader_user);
        $this->assign('is_publish', $is_publish);
        return $this->fetch();
    }

    public function finish_confirm()
    {

        $id = input('id');
        $jdz = new \app\common\model\Jdz();
        $rows = $jdz->find($id);
        if (!($rows['status'] == 19)) {
            $this->error('任务状态异常，请确认所有任务均已完成');
        }
        if ((session('user_info')['userid'] !== $rows['user_id'])) {
            $this->error('确认权限不足');
        }
        $log = json_decode($rows['log'], true);
        //halt($data);
        $log[] = [
            'times' => time(),
            'user' => session('user_info')['userid'],
            'user_name' => session('user_info')['name'],
            'user_head' => session('user_info')['avatar'],
            'type' => 1,
            'message' => '提议人已确认',
            'content' => ''];
        $data['log'] = json_encode($log);
        $data['id'] = $id;
        $data['status'] = 13;
        $data = array_merge($rows->toArray(), $data);
        return $jdz->_save($data);

    }

    //撤回提议
    public function withdraw()
    {
        $id = input('id');
        $rows = model('jdz')->find($id);
        if (session('user_info')['userid'] !== $rows['user_id']) {
            return ['msg' => '撤销权限不足'];
        }
        if ($rows['status'] != 15) {
            return ['msg' => '提议状态不可撤销'];
        }
        $log = json_decode($rows['log'], true);

        $log[] = [
            'times' => time(),
            'user' => session('user_info')['userid'],
            'user_name' => session('user_info')['name'],
            'user_head' => session('user_info')['avatar'],
            'type' => 20,
            'message' => '撤销提议',
            'content' => ''];
        $data['id'] = $rows['id'];
        $data['log'] = json_encode($log);
        $data['id'] = $rows['id'];
        $data['status'] = 20;
        if (model('jdz')->isUpdate(true)->save($data)) {
            return ['msg' => '撤销成功'];
        } else {
            return ['msg' => '撤销失败'];
        }
    }

    //重新编辑
    public function again()
    {
        $id = input('id');
        $rows = model('jdz')->find($id);
        if (session('user_info')['userid'] !== $rows['user_id']) {
            return ['msg' => '编辑权限不足'];
        }
        if ($rows['status'] != 15) {
            return ['msg' => '提议状态不可编辑'];
        }
        $this->assign('rows', $rows);
        if ($this->request->isAjax()) {
            $data = input('post.');
            if($data['is_right'] == 1){
                if(!$data['right_type']){
                    return ['code' => 2, 'msg' => '请选择知识产权类型'];//ajax_return(2,'请选择知识产权类型');
                }
            }
            if ((model('jdz')->isUpdate(true)->save($data)) !== false) {
                return ['code' => 1, 'msg' => '编辑成功'];
            } else {
                return ['code' => 2];
            }
        }
        return $this->fetch();

    }


}